package cn.sc.summer.banner.listener;

import cn.sc.summer.banner.util.PrintUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

/**
 * 类名：banner打印监听类
 *
 * @author a-xin
 * @date 2024/3/20 13:23
 */
@Slf4j
@Component
public class BannerListener implements ApplicationListener<ApplicationReadyEvent> {

    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(@NonNull ApplicationReadyEvent event) {
        if (isGateway()) {
            PrintUtil.printBannerGateway(swaggerEnable(), event.getTimeTaken());
        } else {
            PrintUtil.printBanner(druidEnable(), event.getTimeTaken());
        }
    }

    /**
     * 判断是否是网关服务
     *
     * @return 是否为网关服务
     */
    private Boolean isGateway() {
        try {
            Class.forName("org.springframework.web.reactive.config.DelegatingWebFluxConfiguration");
            return Boolean.TRUE;
        } catch (Exception e) {
            return Boolean.FALSE;
        }
    }

    /**
     * 判断是否存在druid服务
     *
     * @return 是否存在druid服务
     */
    private Boolean druidEnable() {
        try {
            Class.forName("com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure");
            return Boolean.TRUE;
        } catch (Exception e) {
            return Boolean.FALSE;
        }
    }

    /**
     * 判断是否存在druid服务
     *
     * @return 是否存在druid服务
     */
    private Boolean swaggerEnable() {
        try {
            Class.forName("cn.sc.summer.gateway.swagger.SwaggerResourceConfig");
            return Boolean.TRUE;
        } catch (Exception e) {
            return Boolean.FALSE;
        }
    }

}
